# -*- coding: utf-8 -*-
# frontend/components/sidebar.py
"""
侧边栏组件
"""

import streamlit as st
from config.settings import Settings, SUPPORTED_MODELS
from typing import List

def render_sidebar() -> str:
    """渲染侧边栏"""
    with st.sidebar:
        st.markdown("### 🎯 功能导航")
        
        # 页面选择
        pages = ["💬 智能对话", "⚙️ 系统设置", "📊 数据分析"]
        current_page = st.radio(
            "选择页面",
            pages,
            index=pages.index(st.session_state.get("current_page", pages[0])),
            label_visibility="collapsed"
        )
        
        st.markdown("---")
        
        # 快速设置
        st.markdown("### ⚙️ 快速设置")
        
        # 模型选择
        available_models = list(SUPPORTED_MODELS.keys())
        selected_models = st.multiselect(
            "选择AI模型",
            available_models,
            default=st.session_state.get("selected_models", ["gpt-4"]),
            help="选择一个或多个AI模型进行对话"
        )
        st.session_state.selected_models = selected_models
        
        # 温度设置
        temperature = st.slider(
            "响应创意度",
            min_value=0.0,
            max_value=2.0,
            value=st.session_state.get("temperature", 0.7),
            step=0.1,
            help="较低值更保守，较高值更有创意"
        )
        st.session_state.temperature = temperature
        
        # 流式输出
        stream_response = st.checkbox(
            "流式输出",
            value=st.session_state.get("stream_response", True),
            help="实时显示AI响应过程"
        )
        st.session_state.stream_response = stream_response
        
        st.markdown("---")
        
        # 对话管理
        st.markdown("### 💬 对话管理")
        
        col1, col2 = st.columns(2)
        with col1:
            if st.button("🆕 新对话", use_container_width=True):
                st.session_state.conversation_id = None
                st.session_state.chat_history = []
                st.rerun()
        
        with col2:
            if st.button("🗑️ 清空历史", use_container_width=True):
                st.session_state.chat_history = []
                st.success("聊天历史已清空")
                st.rerun()
        
        # 对话列表
        if "conversations" in st.session_state:
            conversations = st.session_state.conversations
            if conversations:
                st.markdown("**最近对话:**")
                for conv in conversations[:5]:
                    if st.button(
                        f"📝 {conv['title'][:20]}...",
                        key=f"conv_{conv['id']}",
                        use_container_width=True
                    ):
                        st.session_state.conversation_id = conv['id']
                        st.rerun()
        
        st.markdown("---")
        
        # 系统状态
        render_system_status()
        
        return current_page

def render_system_status():
    """渲染系统状态"""
    st.markdown("### 📊 系统状态")
    
    # API连接状态
    api_status = check_api_status()
    
    for provider, status in api_status.items():
        color = "🟢" if status["connected"] else "🔴"
        st.markdown(f"{color} **{provider}**: {'已连接' if status['connected'] else '未连接'}")
    
    # 统计信息
    if "chat_history" in st.session_state:
        message_count = len([msg for msg in st.session_state.chat_history if msg["role"] == "user"])
        st.metric("本次对话轮数", message_count)

def check_api_status() -> dict:
    """检查API连接状态"""
    api_keys = st.session_state.get("api_keys", {})
    
    return {
        "OpenAI": {"connected": bool(api_keys.get("openai"))},
        "Anthropic": {"connected": bool(api_keys.get("anthropic"))},
        "Google": {"connected": bool(api_keys.get("google"))}
    }